package team.yidong.fenda.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import team.yidong.fenda.Scheduling.ScheduledTasks;
import team.yidong.fenda.repository.SysUserRepository;
import team.yidong.fenda.service.HospitalService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by xuanlong on 2017/10/21.
 */
@Controller
public class LoginController {
    private final static Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    HospitalService hospitalService;
    @Autowired
    SysUserRepository sysUserRepository;

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/loginCheck")
    public String loginCheck(Model model, HttpServletRequest request, HttpSession session, @RequestParam String userName, @RequestParam String password) {

        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
            subject.login(token);
        } catch (UnknownAccountException ue) {
            model.addAttribute("msg", "账号不存在");
            return "login";
        } catch (IncorrectCredentialsException ie) {
            model.addAttribute("msg", "密码不正确");
            return "login";
        }

        session.setAttribute("loginHospitalId", sysUserRepository.findByUserName(userName).getHospitalId());

        session.setAttribute("loginSysUserName", sysUserRepository.findByUserName(userName).getUserName());
        logger.info(userName + "login");
        if (sysUserRepository.findByUserName(userName).getHospitalId() == 1) {
            return "redirect:/hospital";
        } else if (sysUserRepository.findByUserName(userName).getSysUserRoleId() == 3) {
            return "redirect:/question1";
        } else {
            return "redirect:/images";
        }

    }
}
